package com.itic.system.wx.token.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.service.CrudService;
import com.itic.system.wx.token.persistence.dao.HppWxtokenDao;
import com.itic.system.wx.token.persistence.model.HppWxtoken;
import com.itic.system.wx.token.persistence.model.HppWxtokenExample;
import com.itic.system.wx.token.persistence.model.HppWxtokenExample.Criteria;

@Service
@Transactional
public class HppWxtokenService
     extends CrudService<HppWxtokenDao,HppWxtoken,HppWxtokenExample> {
    @Autowired
    private HppWxtokenDao hppWxtokenDao;
    
    /**
     * 获取有效的token
     * @return
     */
    public String getHppWxtoken(){
    	String token = null;
    	HppWxtokenExample example = new HppWxtokenExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	List<HppWxtoken> list = this.list(example);
    	if(list.size()>0){
    		token = list.get(0).getAccessToken();
    	}
    	return token;
    }
    /**
     * 新增有效的token
     * @param token
     * @return
     */
    public String addNew(HppWxtoken hppWxtoken){
    	String result = FAILED;
    	String token = hppWxtoken.getAccessToken();
    	if(isExist(token)){
    		result = SUCCESS;
    	}else{
    		//置失效现有的
        	abate();
        	//新增有效数据
        	result = this.add(hppWxtoken);
    	}
    	return result;
    }
    /**
     * 判断当前token是否存在
     * @param access_token
     * @return
     */
    public Boolean isExist(String access_token){
    	Boolean isExist = false;
    	HppWxtokenExample example = new HppWxtokenExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	criteria.andAccessTokenEqualTo(access_token);
    	List<HppWxtoken> list = this.list(example);
    	if(list.size()>0){
    		isExist = true;
    	}
    	return isExist;
    }
    /**
     * 置失效当前有效数据
     */
    public void abate(){
    	this.abate();
    }
}